/**
 * Copyright (c) 2008 riaevolution.com, All Rights Reserved.
 *
 * See www.riaevolution.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do
 * so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * */
package com.riaevolution.managers {
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;

	import mx.collections.ArrayCollection;
	import mx.events.ResourceEvent;
	import mx.resources.IResourceManager;
	import mx.resources.ResourceManager;
	import mx.rpc.AsyncToken;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;

	/**
	 * Error management implementation with translation of errors.<br />
	 * This work with the <i>Errors.properties</i> localization file<br />
	 * <h2>A simple implementation</h2>
	 * <code>&lt;mx:Label text="{errorManager.getErrorByCode(102)}" /&gt;</code><br />
	 * And will look for something like <code>resourceManager.getString('Errors','AuthenticationException.102')</code>
	 * return the translation if available else the error defined via the XML.
	 *
	 * <h2>How to write more errors</h2>
	 * You can create a custom XML errors file.
	 * You need a  root node a then error siblings
	 * root->error
	 * each error node must contain the following attributes:
	 * <ul>
	 * <li>code - the unique code
	 * <li>domain - the related domain of this error ProductManagementError
	 * <li>key - the key PRICE_TO_HIGH
	 * <li>message - the default message if no translation avaiable
	 * </ul>
	 * <br />
	 * <b>Note:</b> the message attribute could be a sub.node root->error->message->CDATA of error with CDATA. this is usefull for HTML content.
	 */
	public class ErrorManager extends EventDispatcher implements IErrorManager {
		/**
		 * resource manager reference
		 */
		protected var resourceManager:IResourceManager;

		/**
		 * Constructor
		 */
		public function ErrorManager() {
			super();
			resourceManager=ResourceManager.getInstance();
			if (resourceManager) {
				resourceManager.addEventListener(Event.CHANGE, resourceChanged);
			}
		}

		/**
		 * Esto hace que se pueda utilizar el binding.
		 * @param event
		 *
		 */
		private function resourceChanged(event:Event):void {
			this.dispatchEvent(new Event(Event.CHANGE));
		}

		private static var _instance:ErrorManager;

		//Singleton Instantiation
		public static function get instance():ErrorManager {
			if (_instance == null) {
				_instance=new ErrorManager();
			}
			return _instance;
		}

		private var loader:HTTPService;

		private var errorsdic:Dictionary;

		private function get errorsDic():Dictionary {
			return errorsdic;
		}

		/**
		 * Return an error by code also using parameters.
		 *
		 * @param code
		 * @param params
		 * @param translated
		 * @return
		 *
		 */
		public static function getErrorByCode(code:int, params:Array=null, translated:Boolean=true):String {
			return instance.getErrorByCode(code, params, translated);
		}

		[Bindable("change")]
		/**
		 * return the error by code. this is usedby the singleton
		 * @param code
		 * @param params
		 * @param translated
		 * @return
		 */
		public function getErrorByCode(code:int, params:Array=null, translated:Boolean=true):String {
			if (errorsDic && errorsDic.hasOwnProperty(code)) {
				var err:ErrorDefinition=errorsDic[code];
				var msj:String=String(err.message);
				//	resourceManager.getString('Errors','AuthenticationException.100')
				if (translated) {
					msj=resourceManager.getString('Errors', err.domain + "." + err.code, params);
				}
				//si el resource manager no devolvio contenido retorno lo que esta en el XML.
				if (msj == null || msj.length == 0) {
					msj=String(err.message);
				}
				return msj;
			}
			return "UNKNOW_ERROR_" + code;
		}

		/**
		 * Set the dictionary of errors definitions
		 * @param source
		 */
		public function setErrorDefinition(source:ArrayCollection):void {
			errorsdic=new Dictionary(true);
			var error:Object; //NO PMD
			for each (error in source) {
				if (errorsdic.hasOwnProperty(error.code)) {
					throw new Error("ErrorManager duplicated code for " + error.code); //NO PMD
				}
				errorsdic[error.code]=new ErrorDefinition(error); //NO PMD
			}
			error=null;
			source=null;
			this.dispatchEvent(new Event(Event.CHANGE));
		}

		private function handleFileError(fe:FaultEvent):void {
			if (loader) {
				loader.removeEventListener(FaultEvent.FAULT, handleFileError);
				loader.removeEventListener(ResultEvent.RESULT, handleFileLoaded);
			}
			loader=null;
			throw new Error(fe.fault.faultString);
		}

		private function handleFileLoaded(re:ResultEvent):void {
			if (re.result) {
				var errors:ArrayCollection;
				if (re.result.root.error is ArrayCollection) {
					errors=re.result.root.error;
				}
				else {
					errors=new ArrayCollection([re.result.root.error]);
				}
				setErrorDefinition(errors);
			}
			if (loader) {
				loader.removeEventListener(FaultEvent.FAULT, handleFileError);
				loader.removeEventListener(ResultEvent.RESULT, handleFileLoaded);
			}
			loader=null;
		}

		/**
		 * Load the XML definition of errors.
		 * @param filename
		 * @param params
		 * @return Async Token to monitor the progress if you like
		 */
		public function loadSource(filename:String, params:Object=null):AsyncToken { //NO PMD adobe.ac.pmd.rules.maintanability.forbiddentypes.UseObjectType
			if (loader == null) {
				loader=new HTTPService();
				loader.addEventListener(FaultEvent.FAULT, handleFileError);
				loader.addEventListener(ResultEvent.RESULT, handleFileLoaded);
				loader.resultFormat=HTTPService.RESULT_FORMAT_OBJECT;
			}
			loader.url=filename;
			return loader.send(params);
		}
	}
}

/**
 * This class map the xml information
 * &lt;error
 * 	code="100"
 * 	domain="AuthenticationException"
 * 	key="UNKNOWN_ERROR"
 * 	message="AuthenticationException error" /&gt;
 */
class ErrorDefinition {
	public var code:int;
	public var domain:String;
	public var key:String;
	public var message:String;

	public function ErrorDefinition(item:Object) {
		if (item) {
			this.code=parseInt(item.code);
			this.domain=String(item.domain);
			this.key=String(item.key);
			this.message=String(item.message);
		}
	}
}